/**
 * 210208:canCancel没有和allowEmpty关联的bug
 */

let React=require('react');
import CoolMath from "global-libs/math/cool-math";
import UIComponent from 'ui-components/ui-component';
import SelectGrid from 'ui-components/select-grid/select-grid';
import SelectGroup from 'ui-components/select-grid/select-group';
import DropDown from 'ui-components/drop-down/drop-down';
import ForceOrientation from 'global-libs/global-setup/force-orientation';

/**
 * allowEmpty: 允许空值
 * nameTag：固定显示时的标签
 * fixedTag：固定显示标签
 */
export default class DropDownCustom extends DropDown{
    get allowEmpty(){
        return this.state.allowEmpty;
    }
    set allowEmpty(bol) {
        this.setState({allowEmpty:bol});
    }
    get nameTag(){
        return this.state.nameTag;
    }
    set nameTag(bol) {
        this.setState({nameTag:bol});
    }
    get fixedTag(){
        return this.state.fixedTag;
    }
    set fixedTag(bol) {
        this.setState({fixedTag:bol});
    }
    get index(){
        if(!this.state.allowEmpty){
            this.state.index = CoolMath.clamp(0,this.datas.length-1,this.state.index || 0);
        }
        return this.state.index;
    }
    set index(index) {
        this.setState({index:index});
    }
    get controlledProps(){
        return [...super.controlledProps,"allowEmpty","nameTag","fixedTag"];
    }
    get listStyleTop(){
        if(this.clientRect){
            this._selectGroup.resizeChange();
            let docHeight = ForceOrientation.orientationWidthHeight(document.documentElement.clientWidth,
                document.documentElement.clientHeight).height;
            if((this.clientRect.bottom + this._selectGroup.clientRect.height)>docHeight){
                return UIComponent.fns.convertToRem(-this._selectGroup.clientRect.height)-0.5+"rem";
            }
            return UIComponent.fns.convertToRem(this.clientRect.height)+0.5+"rem";
        }else{
            return 0+"rem";
        }
    }
    get list(){
        let children = [];
        this.datas.forEach((item,index)=>{
            children.push(<SelectGrid className="dropdown-list-item" tagName={index+""} key={"option-"+index}
                                      stopPropagationList={["pointDown"]}
            >
                <span>{this.dataElement(item,true)}</span>
            </SelectGrid>);
        });
        return <SelectGroup className="dropdown-list" key="list" selectedTagName={this.index+""}
                            isVisible={false}
                            canCancel={this.allowEmpty}
                            onValueChange={
                                UIComponent.fns.constObject(this,"_group_change",this.selectChange.bind(this))
                            }
                            onStateChanged={
                                UIComponent.fns.constObject(this,"_group_state_changed",
                                    (component)=>{
                                        if(component.statesHasChanged("isVisible")){
                                            if(UIComponent.fns.TypesCheck.isFunction(this.props.onSwitch)){
                                                this.props.onSwitch(this.tagName,component.isVisible,this);
                                            }
                                        }
                                    }
                                )
                            }
                            callbackComponent={
                                UIComponent.fns.constObject(this,"_group_callback",(component)=>{
                                    this._selectGroup = component;
                                })
                            }
        >
            {children}
        </SelectGroup>;
    }
    get arrow(){
        return <polygon points="-0.5,0 1.5,0 0.5,1"/>;
    }
    get arrowStyle() {
        let style = {
            position: "absolute",
            fill: 'rgba(0,0,0,0.4)',
        };
        style.left = this.arrowPosOffset||'0rem';
        style.top = "-0.5rem";
        style.width = '100%';
        style.height = '0.5rem';
        style.display='none';
        return style;
    }
    getChildren() {
        return [
            UIComponent.fns.constElement(
                this, "_show_text", this.statesHasChanged("index", "textKey", "json"),
                () => {
                    return <span className="dropdown-show-text" key="show-text">
                        {this.dataElement(this.currentData,false) + ""}
                        </span>
                }
            ),
            UIComponent.fns.constElement(
                this, "_icon", false, () => {
                    return <span className="cool-icon-2 drop-down-icon" key="icon" style={{position:'absolute',right:'0.2rem',top:'0.85rem'}}/>;
                }
            ), UIComponent.fns.constElement(
                this, "_list", this.statesHasChanged("json", "textKey"), () => {
                    return this.list;
                }
            ),
            <svg key="arrow" ref="arrow" viewBox="0,0,1,1" style={this.arrowStyle}
            >
                {this.arrow}
            </svg>
        ];
    }
    toggleList(){
        if(!this._selectGroup.isVisible){
            this.resizeChange();
        }
        this._selectGroup.isVisible = !this._selectGroup.isVisible;
        if(this._selectGroup.isVisible){
            this._selectGroup.style = {
                position:'absolute',
                width:"100%",
                height:'auto',
                overflow:'auto',
                left:0,
                top:this.listStyleTop,
                zIndex:10
            };
            this.refs['arrow'].style.display='block';
        }else{
            this.refs['arrow'].style.display='none';
        }
    }
    folded(){
        if(this._selectGroup.isVisible){
            this._selectGroup.isVisible = false;
        }
        this.refs['arrow'].style.display='none';
    }
    domMount(){
        super.domMount();
        this._windowEvent = UIComponent.fns.DOMCrossPlatformEvent.createEvent(window);
        this._windowEvent.addEventListener("pointClick",(e)=>{
            this.folded();
        });
        this._windowEvent.start();
    }
    selectChange(remove,add,isManual){
        super.selectChange(remove,add,isManual);
        if(this.refs['arrow'])this.refs['arrow'].style.display='none';
    }
    addWindowEvent() {
        this._windowEvent = UIComponent.fns.DOMCrossPlatformEvent.createEvent(window);
        this._windowEvent.addEventListener("pointUp",(e)=>{
            clearTimeout(this._hideTimeout);
            this._hideTimeout = setTimeout(()=>{
                if(this._selectGroup.isVisible){
                    this._selectGroup.isVisible = false;
                    this.refs['arrow'].style.display='none';
                }
            },50);
        });
        this._windowEvent.start();
    }
    dataElement(data,isList=true){
        if(isList){
            try{
                return  this.dataRender(data);
            }catch (e) {
                return null;
            }
        }else{
            try{
                return  this.fixedTag?this.nameTag:this.dataRender(data);
            }catch (e) {
                return this.nameTag?this.nameTag:null;
            }
        }
    }
}